/**
 * WeChat JS SDK config and pay utility
 */

;(function(global, factory) {
  if (typeof define === 'function' && define.amd) {
    define(['wx'], factory)
  } else if (typeof module === 'object' && module.exports) {
    module.exports = factory(require('wx'))
  } else {
    global.wxutil = factory(global.wx)
  }
})(this, function(wx) {
  var wxutil = {

    /**
     * Inject WeChat JS SDK configuration
     * 
     * @param  {Object} config WeChat JS SDK configuration object
     */
    config: function(config) {
      var debugMode = location.search.indexOf('debug=true') > 0,
        apis = Array.prototype.slice.call(arguments, 1)

      wx.config({
        debug: debugMode,
        appId: config.appid,
        timestamp: config.timestamp,
        nonceStr: config.nonce_str,
        signature: config.signature,
        jsApiList: apis
      })
    },

    /**
     * Invoke WeChat JS to pay
     * 
     * @param  {Object}   config  WeChat payement configuration object
     * @param  {Function} success success callback function after payment
     */
    invokePay: function(config, success) {
      wx.ready(function() {
        wx.chooseWXPay({
          timestamp: config.timestamp,
          nonceStr: config.nonce_str,
          package: 'prepay_id=' + config.prepayId,
          signType: 'MD5',
          paySign: config.paySign,
          success: function(res) {
            success(res)
          }
        })
      })
    }
  }
  return wxutil
})

